package com.tea.room.service.tea.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tea.room.dao.tea.HouseInfoDao;
import com.tea.room.dao.tea.TeaOrderDao;
import com.tea.room.model.Return;
import com.tea.room.model.tea.HouseInfo;
import com.tea.room.model.tea.TeaOrder;
import com.tea.room.service.door.DoorService;
import com.tea.room.service.tea.OperationService;
import com.tea.room.service.tea.TeaOrderService;
import com.tea.room.service.wechat.PayService;
import com.tea.room.util.DateUtils;
import com.tea.room.util.JsonUtil;

@Service
public class OperationServiceImpl implements OperationService {

    private static Logger logger = LoggerFactory.getLogger(OperationServiceImpl.class);
    
    @Autowired
    private TeaOrderService teaOrderService;
    
    @Autowired
    private DoorService doorService;
    
    @Autowired
    private PayService payService;
    
    @Autowired
    private HouseInfoDao houseInfoDao;
    
    @Autowired
    private TeaOrderDao teaOrderDao;
    
    @Override
    @Transactional
    public Return addMtOrder(HttpServletRequest request) {
        Map<String, String> params = getParams(request, "teacode", "serno", "time0", "status", "time1", "time2", "total", "mt_code");
        logger.info("入参：" + JsonUtil.mapToJsonObject(params));
        //校验参数
        Return rn = checkParam(params);
        if(!rn.getIsSuccessflag()){
            return rn;
        }
        /**
         * 校验时段
         */
        Map<String, Object> result = teaOrderService.checkTime_interval(params.get("teacode"), params.get("time0").replace(" ", ""), params.get("total"));
        if((boolean) result.get("flag")){
            rn.setIsSuccessflag(false);
            rn.setMessage("选择时段已被预订,请刷新页面！");
            return rn;
        }
        //获取密码
        Integer password = (int) (Math.random() * 899999 + 100000);
        logger.info("获取门锁密码：" + password);
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start = new Date();
        Date end = new Date();
        try {
            start = format.parse(params.get("time1"));
            end = format.parse(params.get("time2"));
            logger.info("下发密码开始时间：" + start.getTime() + " - 结束时间：" + end.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        result.put("lockId", params.get("lockId"));// 门锁ID
        result.put("validStart", start.getTime());// 开始时间时间戳到毫秒
        result.put("validUntil", end.getTime());// 结束时间 时间戳到毫秒
        result.put("holder", "美团");//持有人 可选
        result.put("phoneNumber", "17600110458");// 手机号 可选
        result.put("password", password);//密码
        result.put("subType", "4");// 密码类型， 1=永久，2=单次，4=限时
        result.put("canOpenAntilock", true);// 是否可以开反锁,true：可以开,false:不能开
        result.put("phoneCountry", "+86");
        String string = doorService.onlinePassword(result);
        logger.info("下发门锁密码返回：" + string);
        //保存订单
        TeaOrder order = new TeaOrder();
        order.setTeaCode(params.get("teacode"));//茶楼编码
        order.setSerno(params.get("serno"));//订单编码
        order.setTime_interval(params.get("time0"));//订单时段
        order.setTotal(params.get("total"));//累计时长
        order.setPrice(0.00);//订单金额
        order.setPayStatus("Y");
        order.setStatus("已支付");
        order.setPassword(password.toString());
        order.setStart(start);//开始时间
        order.setReminder(end);//到期时间
        order.setOpenId(params.get("mt_code"));//先暂存验证码，验证成功更新openid
        order.setCrt_date(new Date());
        order.setMdf_date(new Date());
        teaOrderDao.insert(order);
        //已预订时段更新
        String flag = payService.updateReserveTime(order);
        if(flag.equals("-1")){//时段已被预定，退款，并通知用户
            logger.info("时段已被预定，通知用户更改预定时间flag：" + flag);
            rn.setIsSuccessflag(false);
            rn.setMessage("时段已被预定，通知用户更改预定时间");
        }
        return rn;
    }
    
    /**
     * 获取参数
     * @param request
     * @param paramName
     * @return
     */
    private Map<String,String> getParams(HttpServletRequest request, String... items){
        Map<String,String> map = new HashMap<String, String>();
        for(String item : items){
            map.put(item, request.getParameter(item));
            if("time0".equals(item)){
                map.put(item, request.getParameter(item).replace(" ", ""));
            }
        }
        return map;
    }
    
    /**
     * 参数校验
     * @param params
     * @return
     */
    private Return checkParam(Map<String, String> params){
        Return rn = new Return();
        rn.setIsSuccessflag(true);
        HouseInfo houseInfo = new HouseInfo();
        houseInfo.setTeaCode(params.get("teacode"));
        HouseInfo info = houseInfoDao.query(houseInfo);
        if(info == null){
            rn.setIsSuccessflag(false);
            rn.setMessage("茶室不存在");
            return rn;
        }
        //获取茶室门锁ID
        params.put("lockId", info.getLockId());
        Map<String, Long> map = DateUtils.getTimeDifference(params.get("time1"), params.get("time2"));
        Long sum = map.get("days") * 24 + map.get("hours");
        Double tt = 0.0;
        if(map.get("minutes") > 0){
            tt = sum + 0.5;
        }else{
            tt = sum + 0.0;
        }
        Double total = Double.valueOf(params.get("total"));
        if(!tt.equals(total)){
            rn.setIsSuccessflag(false);
            rn.setMessage("累计时长与授权时间不匹配");
            return rn;
        }
        String time0 = params.get("time0");
        String time = params.get("time1").substring(11, 16) + "-" + params.get("time2").substring(11, 16);
        if(!time0.equals(time)){
            rn.setIsSuccessflag(false);
            rn.setMessage("预定时段与授权时间不匹配");
            return rn;
        }
        
        return rn;
    }

}
